#include "CsvExporter.h"
#include "DatabaseService.h"
#include "utils/Logger.h"
#include <QFile>
#include <QTextStream>
#include <QSqlQuery>
#include <QSqlError>
#include <QFileInfo>
#include <QDir>
#include <QDebug>

CsvExporter::CsvExporter(QObject *parent)
    : QObject(parent)
{
}

CsvExporter::~CsvExporter()
{
}

// 导出实时数据
bool CsvExporter::exportRealtimeData(const QString &filePath,
                                     const QString &deviceId,
                                     const QDateTime &startTime,
                                     const QDateTime &endTime)
{
    return exportData(filePath, RealtimeData, deviceId, startTime, endTime);
}

// 导出分钟统计数据
bool CsvExporter::exportMinuteStatistics(const QString &filePath,
                                         const QString &deviceId,
                                         const QDateTime &startTime,
                                         const QDateTime &endTime)
{
    return exportData(filePath, MinuteStatistics, deviceId, startTime, endTime);
}

// 导出小时统计数据
bool CsvExporter::exportHourStatistics(const QString &filePath,
                                       const QString &deviceId,
                                       const QDateTime &startTime,
                                       const QDateTime &endTime)
{
    return exportData(filePath, HourStatistics, deviceId, startTime, endTime);
}

// 通用导出方法
bool CsvExporter::exportData(const QString &filePath,
                             ExportType type,
                             const QString &deviceId,
                             const QDateTime &startTime,
                             const QDateTime &endTime)
{
    qInfo() << "CsvExporter: 开始导出数据到" << filePath;

    // 确保目录存在
    QFileInfo fileInfo(filePath);
    QDir dir = fileInfo.absoluteDir();
    if (!dir.exists())
    {
        if (!dir.mkpath("."))
        {
            setError("无法创建目录: " + dir.path());
            return false;
        }
    }

    // 打开文件
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        setError("无法打开文件: " + file.errorString());
        return false;
    }

    QTextStream stream(&file);
    stream.setCodec("UTF-8");

    // 写入 UTF-8 BOM（兼容 Excel）
    if (!writeUtf8Bom(stream))
    {
        file.close();
        return false;
    }

    // 构建 SQL 查询
    QString tableName;
    QString headerLine;
    QString selectFields;

    switch (type)
    {
    case RealtimeData:
        tableName = "realtime_data";
        headerLine = "时间戳,设备ID,温度(℃),压力(kPa),流量(L/min)";
        selectFields = "timestamp, device_id, temperature, pressure, flow";
        break;

    case MinuteStatistics:
        tableName = "minute_statistics";
        headerLine = "时间戳,设备ID,温度平均,温度最大,温度最小,压力平均,压力最大,压力最小,流量平均,流量最大,流量最小,采样数";
        selectFields = "timestamp, device_id, temp_avg, temp_max, temp_min, "
                       "pressure_avg, pressure_max, pressure_min, "
                       "flow_avg, flow_max, flow_min, sample_count";
        break;

    case HourStatistics:
        tableName = "hour_statistics";
        headerLine = "时间戳,设备ID,温度平均,温度最大,温度最小,压力平均,压力最大,压力最小,流量平均,流量最大,流量最小,采样数";
        selectFields = "timestamp, device_id, temp_avg, temp_max, temp_min, "
                       "pressure_avg, pressure_max, pressure_min, "
                       "flow_avg, flow_max, flow_min, sample_count";
        break;
    }

    // 写入表头
    stream << headerLine << "\n";

    // 构建查询条件
    QString whereClause = "WHERE 1=1";
    if (!deviceId.isEmpty())
    {
        whereClause += QString(" AND device_id = '%1'").arg(deviceId);
    }
    if (startTime.isValid())
    {
        whereClause += QString(" AND timestamp >= '%1'").arg(startTime.toString("yyyy-MM-dd HH:mm:ss"));
    }
    if (endTime.isValid())
    {
        whereClause += QString(" AND timestamp <= '%1'").arg(endTime.toString("yyyy-MM-dd HH:mm:ss"));
    }

    // 执行查询
    QString sql = QString("SELECT %1 FROM %2 %3 ORDER BY timestamp ASC")
                      .arg(selectFields, tableName, whereClause);

    QSqlDatabase db = DatabaseService::instance()->database();
    QSqlQuery query(db);

    if (!query.exec(sql))
    {
        setError("查询失败: " + query.lastError().text());
        file.close();
        return false;
    }

    // 获取总行数
    int totalRows = 0;
    if (query.last())
    {
        totalRows = query.at() + 1;
        query.first();
        query.previous();
    }

    // 写入数据
    int currentRow = 0;
    while (query.next())
    {
        currentRow++;

        if (type == RealtimeData)
        {
            // 实时数据格式
            QString timestamp = query.value(0).toString();
            QString devId = query.value(1).toString();
            double temperature = query.value(2).toDouble();
            double pressure = query.value(3).toDouble();
            double flow = query.value(4).toDouble();

            stream << QString("%1,%2,%3,%4,%5\n")
                          .arg(timestamp)
                          .arg(devId)
                          .arg(temperature, 0, 'f', 1) // 温度保留 1 位小数
                          .arg(pressure, 0, 'f', 1)    // 压力保留 1 位小数
                          .arg(flow, 0, 'f', 2);       // 流量保留 2 位小数
        }
        else
        {
            // 统计数据格式
            QString timestamp = query.value(0).toString();
            QString devId = query.value(1).toString();
            double tempAvg = query.value(2).toDouble();
            double tempMax = query.value(3).toDouble();
            double tempMin = query.value(4).toDouble();
            double pressureAvg = query.value(5).toDouble();
            double pressureMax = query.value(6).toDouble();
            double pressureMin = query.value(7).toDouble();
            double flowAvg = query.value(8).toDouble();
            double flowMax = query.value(9).toDouble();
            double flowMin = query.value(10).toDouble();
            int sampleCount = query.value(11).toInt();

            stream << QString("%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11,%12\n")
                          .arg(timestamp)
                          .arg(devId)
                          .arg(tempAvg, 0, 'f', 1)
                          .arg(tempMax, 0, 'f', 1)
                          .arg(tempMin, 0, 'f', 1)
                          .arg(pressureAvg, 0, 'f', 1)
                          .arg(pressureMax, 0, 'f', 1)
                          .arg(pressureMin, 0, 'f', 1)
                          .arg(flowAvg, 0, 'f', 2)
                          .arg(flowMax, 0, 'f', 2)
                          .arg(flowMin, 0, 'f', 2)
                          .arg(sampleCount);
        }

        // 发送进度信号
        if (currentRow % 100 == 0 || currentRow == totalRows)
        {
            emit exportProgress(currentRow, totalRows);
        }
    }

    file.close();

    qInfo() << "CsvExporter: 导出完成，共" << currentRow << "行数据";

    // 记录操作日志
    Logger::instance()->logOperation("export_csv", filePath,
                                     QString("导出 %1 行数据").arg(currentRow));

    emit exportFinished(true, filePath);
    return true;
}

// 写入 UTF-8 BOM
bool CsvExporter::writeUtf8Bom(QTextStream &stream)
{
    // UTF-8 BOM: EF BB BF
    QByteArray bom;
    bom.append(static_cast<char>(0xEF));
    bom.append(static_cast<char>(0xBB));
    bom.append(static_cast<char>(0xBF));

    QFile *file = qobject_cast<QFile *>(stream.device());
    if (file)
    {
        file->write(bom);
        return true;
    }

    return false;
}

// 设置错误信息
void CsvExporter::setError(const QString &error)
{
    m_lastError = error;
    qWarning() << "CsvExporter 错误:" << error;
}
